#!/bin/sh

tsamp=`date +"%m%d_%H%M%S"`
fs="/sdcard/$tsamp.csv"

touch $fs

echo "time,case,temp,CPU0,CPU1,CPU2,CPU3,CPU4,CPU5,CPU6,CPU7,CPU%,CPU_proc%,GPU,GPU%,fps" >> $fs

cpu_idle="-1%"

case_path="/sdcard/case"
fps_path="/sdcard/unity_fps"

# 避免没有文件
echo "null" > $case_path
echo "-1" > $fps_path

top_idle(){
    tops=`top -b -n 1 -o PID -o %CPU -p 1`
    ss=${tops##*sys }

    ss=${ss%%idle*}
    cpu_idle=$ss
}

# 0~7
# /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq
# cat /sys/class/kgsl/kgsl-3d0/gpuclk \
#    && cat /sys/class/kgsl/kgsl-3d0/gpu_busy_percentage
dp_once(){
    # temp array
    sz=14
    cpu_sz=8
    # temperature array
    ta=()
    # cpu freq array
    fa=()
    sum=0.0
    aver=0.0
    i=0
    j=0
    
    while [ $i -lt $sz ]
    do
        # echo "i = $i"
        n=`expr $i + 20`
        tp=/sys/class/thermal/thermal_zone$n/temp
        # echo "  >> tp : $tp"
        tt=`cat $tp`
        # echo "  >> tt = $tt"
        #ta[i]=`expr ta[$i] / 1000`
        ta[i]=$(echo "scale=2; $tt / 1000" | bc)
        #echo "  >> ta[$i] = ${ta[$i]}"
        sum=$(echo "$sum + ${ta[$i]}" | bc)
        #echo "  >> sum = $sum"
        #echo "-----------------------"
        i=`expr $i + 1`
    done
    aver=$(echo "scale=2; $sum / 14" | bc)

    mdate=`date +"%m:%d %H:%M:%S"`
    
    while [ $j -lt $cpu_sz ]
    do
        cfp=/sys/devices/system/cpu/cpu$j/cpufreq/scaling_cur_freq
	fa[j]=`cat $cfp`

        j=`expr $j + 1`
    done

    # get CPU idle
    top_idle
    gpu=`cat /sys/class/kgsl/kgsl-3d0/gpuclk`
    gpu_per=`cat /sys/class/kgsl/kgsl-3d0/gpu_busy_percentage`
    

    case_content=`cat $case_path`
    fps=`cat $fps_path`
    pcpu_proc=`cat /sdcard/mcpu_idle`
    str="$mdate,$case_content,$aver,${fa[0]},${fa[1]},${fa[2]},${fa[3]},${fa[4]},${fa[5]},${fa[6]},${fa[7]},$cpu_idle,$pcpu_proc,$gpu,$gpu_per,$fps"
    echo "$str"
    
    echo $str >> $fs
}

/bin/cpu_idle &

while true
do
    dp_once
    sleep 1
done    
